<?php
declare (strict_types = 1);

namespace app\controller\admin;

use think\facade\Validate;
use think\response\Json;
use app\model\Apply;
use tp5er\Backup\facade\Backup;

class AdminRestore extends AdminBase
{

	protected $middleware = [
		'app\middleware\AdminLogin',
		'app\middleware\AdminAuth'
	];

	private string $menuName = '数据还原';


    /**
     * 显示资源列表
     * @throws
     * @return Json
     */
    public function index():Json
    {
        $data = Backup::files();

        $data = array_reverse($data);

        foreach ($data as &$d){
            $d['create_time'] = substr($d['system_name'],0,4).'-'.substr($d['system_name'],4,2).'-'.substr($d['system_name'],6,2).' '.substr($d['system_name'],8,2).':'.substr($d['system_name'],10,2).':'.substr($d['system_name'],12,2);
        }

        $this->result['data'] = $data;

		return returnAdmin($this->request,$this->result,$this->menuName.'-列表',$this->adminInfo);
    }

    /**
	 * 还原
	 * @throws
	 * @return Json
	 */
	public function restore():Json
	{
        //获取form表单
        $file = input('name','','trim');

        try{
            if(!$file){
                throw new \Exception('无效参数');
            }

            Backup::import($file);

        }catch (\Exception $e){
            $this->result['code'] = 500;
            $this->result['msg'] = $e->getMessage();
        }

		return returnAdmin($this->request,$this->result,$this->menuName.'-编辑',$this->adminInfo);
	}

    /**
     * 下载
     * @throws
     */
    public function download(){
        $file = input('file','','trim');

        return backup_download($file);
    }

    /**
     * 删除指定资源
     * @throws
     * @return Json
     */
    public function delete():Json
    {

        $name = (string) input('name','','trim');
        try {
            //批量删除
            if (!$name) {
                throw new \Exception('无效参数');
            }
            //指定文件删除
            unlink($name);

            $this->result['msg'] = '删除文件：'.$name;
        }catch (\Exception $e){
            $this->result['code'] = 500;
            $this->result['msg'] = $e->getMessage();
        }

        return returnAdmin($this->request,$this->result,$this->menuName.'-删除',$this->adminInfo);
    }



}
